package sheep.taskpool;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义任务线程池配置
 *
 * @author lizy
 * @date 2021/09/23
 */
@Configuration
public class TaskExecutePoolConfig {

    /**
     * 核心池大小
     */
    private int corePoolSize = 5;
    /**
     * 最大池大小
     */
    private int maxPoolSize = 10;
    /**
     * 队列容量
     */
    private int queueCapacity = 100;
    /**
     * 活跃时间
     */
    private int keepAliveSeconds = 30;

    @Bean
    public Executor getFileExecutor() {
        ThreadPoolTaskExecutor executor = new MdcThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(corePoolSize);
        //最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //队列容量
        executor.setQueueCapacity(queueCapacity);
        //活跃时间
        executor.setKeepAliveSeconds(keepAliveSeconds);
        //线程名字前缀
        executor.setThreadNamePrefix("executor-file-");
        //线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //当pool已经到达max size的时候，如何处理新任务,CallerRunsPolicy,由调用者所在的线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    @Bean
    public Executor getSampleExecutor() {
        ThreadPoolTaskExecutor executor = new MdcThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(corePoolSize);
        //最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //队列容量
        executor.setQueueCapacity(queueCapacity);
        //活跃时间
        executor.setKeepAliveSeconds(keepAliveSeconds);
        //线程名字前缀
        executor.setThreadNamePrefix("executor-sample-");
        //线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //当pool已经到达max size的时候，如何处理新任务,CallerRunsPolicy,由调用者所在的线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}